package com.song.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * @Author 宋伟宁
 * @Date 2023/9/7
 * @Version 1.0
 **/
public class MyBatisUtil {

    private static SqlSessionFactory factory;
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();

    static{
        try {
            factory =new  SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static SqlSessionFactory getFactory(){
         return  factory;
    }

    public static SqlSession getSession(){
         SqlSession session = threadLocal.get();
         if(session == null){
             session = factory.openSession();
             threadLocal.set(session);
         }
         return session;
    }
}
